package com.ruoyi.app.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.app.domain.user.Register;
import com.ruoyi.app.service.AppUserService;
import com.ruoyi.common.config.PasswordConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.comlbs.OrgTypeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.AESUtils;
import com.ruoyi.system.utils.AvatarGenerateUtil;
import com.ruoyi.system.utils.ComLbsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;

/**
 * 描述
 * 作者 ZhangPing
 * 创建时间 2023/9/27 17:24
 */
@Slf4j
@Service
public class AppUserServiceImpl implements AppUserService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PasswordConfig passwordConfig;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDeptService deptService;

    /**
     * APP用户注册
     *
     * @param register
     */
    @Transactional
    @Override
    public JSONObject register(Register register) {
        if (!ComLbsUtils.userNameCheck(register.getUsername())) {
            throw new ServiceException("账号由字母数字下划线组成且开头必须是字母，不能超过16位");
        }
        //密码解密
        String password = AESUtils.decrypt(register.getPassword(), passwordConfig.getSecretKey().getBytes(StandardCharsets.UTF_8));
        if (!ComLbsUtils.passwordCheck(password)) {
            throw new ServiceException("新密码要求长度8位以上、包含大小写字母、数字和特殊符号");
        }
        userService.checkExistUserName(register.getUsername());
        userService.checkExistMobile(register.getMobile());
        //校验短信验证码
        String smsCodeKey = "SmsCode:" + register.getMobile();
        String cacheCode = redisCache.getCacheObject(smsCodeKey);
        if (StringUtils.isEmpty(cacheCode) || !register.getCodeSMS().equals(cacheCode)) {
            throw new ServiceException("验证码错误！");
        }
        //删除短信验证码
        redisCache.deleteObject(smsCodeKey);
        //APP注册用户在个人用户公司节点下新增个人用户的公司
        String appUserCompanyId = configService.selectConfigByKey("app_user_company_id");
        if (StringUtils.isEmpty(appUserCompanyId)) throw new ServiceException("个人用户公司不存在，请联系管理员！");
        SysDept dept = new SysDept()
                .setParentId(Long.valueOf(appUserCompanyId))
                .setDeptName(register.getMobile())
                .setShortName(register.getMobile())
                .setLeader(register.getUsername())
                .setPhone(register.getMobile())
                .setType(OrgTypeEnum.NODE.getCode())
                .setCreateBy(UserConstants.ADMIN_ID)
                .toExtentEntity(SysDept.class);
        deptService.insertDept(dept);
        //新增用户,设置个人用户角色，并把账号添加到该公司下
        String appUserRoleId = configService.selectConfigByKey("app_user_role_id");
        if (StringUtils.isEmpty(appUserRoleId)) throw new ServiceException("个人用户角色不存在，请联系管理员！");
        SysUser user = new SysUser()
                .setCreateBy(UserConstants.ADMIN_ID)
                .toExtentEntity(SysUser.class)
                .setDeptId(dept.getDeptId())
                .setRoleIds(new Long[]{Long.valueOf(appUserRoleId)})
                .setUserName(register.getUsername())
                .setNickName(register.getUsername())
                .setUserType(1)//用户类型（0系统用户，1移动端用户，2驾驶员，3管理员）
                .setPhonenumber(register.getMobile())
                .setPassword(SecurityUtils.encryptPassword(password));
        userService.insertUser(user);
        return new JSONObjectPro()
                .put("name", user.getNickName())
                .put("username", user.getUserName())
                .put("companyName", dept.getDeptName())
				.put("photo", user.getAvatar())
                .put("userType", user.getUserType())
                .put("phoneNumber", register.getMobile());
    }

}
